package com.service;

import com.entity.VehicleInsurance;
import com.repository.VehicleInsuranceRepository;
import com.dto.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Optional;

@Service
@Transactional
public class VehicleInsuranceService {

    @Autowired
    private VehicleInsuranceRepository vehicleInsuranceRepository;

    /**
     * 保存车辆保险信息
     *
     * @param vehicleInsurance 车辆保险信息
     * @return 保存后的对象
     */
    public VehicleInsurance save(VehicleInsurance vehicleInsurance) {
        if (vehicleInsurance.getId() == null) {
            vehicleInsurance.setCreateTime(new Date());
        }
        vehicleInsurance.setUpdateTime(new Date());
        return vehicleInsuranceRepository.save(vehicleInsurance);
    }

    /**
     * 根据ID删除车辆保险信息
     *
     * @param id ID
     */
    public void deleteById(Integer id) {
        vehicleInsuranceRepository.deleteById(id);
    }

    /**
     * 根据ID获取车辆保险信息
     *
     * @param id ID
     * @return 车辆保险信息
     */
    @Transactional(readOnly = true)
    public Optional<VehicleInsurance> findById(Integer id) {
        return vehicleInsuranceRepository.findById(id);
    }

    /**
     * 分页查询车辆保险信息
     *
     * @param pageNum  页码
     * @param pageSize 每页数量
     * @return 车辆保险信息分页数据
     */
    @Transactional(readOnly = true)
    public Page<VehicleInsurance> findAll(int pageNum, int pageSize) {
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize, Sort.by("id").descending());
        return vehicleInsuranceRepository.findAll(pageable);
    }

    /**
     * 根据车牌号查询车辆保险信息
     *
     * @param plateNumber 车牌号
     * @param pageNum     页码
     * @param pageSize    每页数量
     * @return 车辆保险信息分页数据
     */
    @Transactional(readOnly = true)
    public Page<VehicleInsurance> findByPlateNumberContaining(String plateNumber, int pageNum, int pageSize) {
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize, Sort.by("id").descending());
        return vehicleInsuranceRepository.findByPlateNumberContaining(plateNumber, pageable);
    }
}